package com.threadpool.pool.queue;

import java.util.PriorityQueue;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 * 优先级任务队列
 * </p>
 *
 * @author 桌角的眼镜
 * @version 1.0
 * @since 2025/5/14 0:50
 */
public class PriorityTaskQueue<T extends Comparable<T>> implements CustomBlockingQueue<T> {
    private final PriorityQueue<T> queue = new PriorityQueue<>();
    private final int capacity;

    public PriorityTaskQueue(int capacity) {
        this.capacity = capacity;
    }

    @Override
    public synchronized boolean offer(T task) {
        if (queue.size() >= capacity) {
            return false;
        }
        queue.offer(task);
        notifyAll();
        return true;
    }

    @Override
    public synchronized T poll(long timeout, TimeUnit unit) {
        long deadline = System.nanoTime() + unit.toNanos(timeout);
        while (queue.isEmpty()) {
            long remaining = deadline - System.nanoTime();
            if (remaining <= 0) {
                return null;
            }
            try {
                TimeUnit.NANOSECONDS.timedWait(this, remaining);
            } catch (InterruptedException e) {
                return null;
            }
        }
        return queue.poll();
    }

    @Override
    public synchronized T poll() {
        return queue.poll();
    }
}
